package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

/**
 * 审核流程定义
 */
@Service
public class BpmnInfoServiceImpl implements IBpmnInfoService {
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public void save(BpmnInfo bpmnInfo) {
        //前台传递过来的数据不能直接使用
        BpmnInfo newObj = new BpmnInfo();

        bpmnInfoMapper.insert(newObj);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteBatch(String ids) {

    }

    @Override
    public void update(BpmnInfo bpmnInfo) {
        BpmnInfo oldObj = this.get(bpmnInfo.getId());

        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deploy(MultipartFile file, String bpmnLabel, String bpmnType, String info) throws IOException {
        //获取原始 文件名字 bus_service_car_package.bpmn
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String subName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //验证传入的参数必须是bpmn格式
        if (!"bpmn".equalsIgnoreCase(subName)){
            throw new BusinessException("流程部署文件必须是bpmn格式!");
        }
        //进行部署 创建部署对象 仓库service
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(originalFilename, file.getInputStream())
                .deploy();
        //根据部署对象查询 流程定义对象  一次部署-->一个流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        //获取流程定义对象 获取流程定义对象的key 和 Version
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setBpmnLabel(bpmnLabel);
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());     //部署时间
        bpmnInfo.setProcessDefinitionKey(processDefinition.getKey());       //activity 流程定义生成的key
        bpmnInfo.setVersion(processDefinition.getVersion());        //版本
        //插入到bpmnInfo
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public InputStream getInputStreamByType(Long id, String type) {
        //通过id查询bpmnInfo对象
        BpmnInfo bpmnInfo = this.get(id);
        //通过bpmnInfo对象 获取该对象中的 key 和 version
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        Integer version = bpmnInfo.getVersion();
        //通过获取到的 key 和 version 查询出当前流程对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processDefinitionKey)
                .processDefinitionVersion(version)
                .singleResult();
        //获取部署id  和文件名
        String deploymentId = processDefinition.getDeploymentId();
        String xmlName = processDefinition.getResourceName();
        //定义一个 输入流
        InputStream is = null;
        //判断文件类型  需要哪种输入流
        if ("xml".equalsIgnoreCase(type)){
            //需要有xml 的文件名称
            //获取xml文件
             is = repositoryService.getResourceAsStream(deploymentId, xmlName);
        }else if ("png".equalsIgnoreCase(type)){
            //流程图对象模型
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            //流程文件图片生成器
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            // generator.generateDiagram(bpmn模型，需要高亮节点的id集合，需要高亮的链接id集合，字体，字体，字体)
            is = generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST,Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else {
            throw new BusinessException("请传递正确的文件类型格式");
        }
        return is;
    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = this.get(id);
        //查询当前流程定义有哪些流程实例
        List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .list();
        //找到所有对应的业务标识,通过业务标识更新其状态为(初始化)
        for (ProcessInstance processInstance : processInstanceList) {
            String businessKey = processInstance.getBusinessKey();
            // TODO 查询所有的流程实例，找到业务标识，更新业务标识信息
        }
        //级联删除 流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .processDefinitionVersion(bpmnInfo.getVersion())
                .singleResult();
        repositoryService.deleteDeployment(processDefinition.getDeploymentId(),true);
        //删除业务表数据
        bpmnInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public BpmnInfo getByBpmnType(String auditType) {
        return bpmnInfoMapper.getByBpmnType(auditType);
    }
}
